﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Globalization;

namespace Kokomo
{
	public class HexConverter : TypeConverter
	{
		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
		{
			if (destinationType == null) throw new ArgumentNullException("destinationType");

			bool canConvert =
				(destinationType == typeof(string))
				;

			return canConvert;
		}

		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
		{
			if (value == null) throw new ArgumentNullException("value");
			if (destinationType == null) throw new ArgumentNullException("destinationType");
			if (destinationType != typeof(string)) throw new InvalidOperationException("Can only convert to string");

			int digits;
			Type valueType = value.GetType();
			if ((valueType == typeof(byte)) || (valueType == typeof(sbyte))) digits = 2;
			else if ((valueType == typeof(short)) || (valueType == typeof(ushort))) digits = 4;
			else if ((valueType == typeof(int)) || (valueType == typeof(uint))) digits = 8;
			else if ((valueType == typeof(long)) || (valueType == typeof(ulong))) digits = 16;
			else throw new ArgumentException("Cannot convert " + valueType.FullName);

			long number = ((IConvertible)value).ToInt64(NumberFormatInfo.CurrentInfo);

			string numberFormat = "X" + digits;
			string text = "0x" + number.ToString(numberFormat);

			return text;
		}
	}
}
